<template>
  <div class="app-container">
    <div class="search-container">
      <div class="search-title">查询条件</div>
      <div class="search-form">
        <div class="form-row">
          <div class="form-column">
              <span class="column-title">装备名称</span>
              <el-input v-model="queryParams.equipmentName" placeholder="请输入" class="input-w150" clearable
                @keyup.enter.native="handleQuery" />
            </div>
          <div class="form-column">
            <span class="column-title">单位</span>
            <treeselect class="input-w150" v-model="queryParams.unitCode" :options="deptTreeList" :show-count="true"
              placeholder="请选择" />
          </div>
          <div class="form-column">
            <span class="column-title">来源</span>
            <el-select v-model="queryParams.sourceId" placeholder="请选择" class="input-w150" clearable filterable>
              <el-option v-for="dict in dict.type.sys_equipment_source" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </div>
          <div class="form-column">
            <span class="column-title">创建时间</span>
            <el-date-picker v-model="createTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" type="daterange"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" class="input-w383" clearable>
            </el-date-picker>
          </div>
          <div class="form-column">
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </div>
    </div>

    <div class="body-container">
      <div class="operation-bar">
        <div class="bar-title">装备情况列表</div>
        <div class="bar-btn__wrapper">
          <div class="bar-btn" @click="handleAdd">
            <i class="el-icon-plus"></i>新增
          </div>
          <div class="bar-btn" @click="handleUploadFile"><i class="el-icon-upload2"></i>导入</div>
          <div class="bar-btn" @click="handleDownLoad"><i class="el-icon-download"></i>导出</div>
        </div>
      </div>

      <el-table v-loading="loading" stripe :data="dataList">
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <el-table-column label="单位" prop="unitName" align="center" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.unitFullName }}
            <!-- {{ getDeptName(scope.row.unitFullName) }} -->
          </template>
        </el-table-column>
        <el-table-column label="装备名称" prop="equipmentName" align="center" min-width="100" />
        <el-table-column label="型号" prop="modelName" align="center" min-width="100" />
        <el-table-column label="编号" prop="equipmentEncoded" align="center" />
        <el-table-column label="完好率" prop="integrityRate" align="center">
          <template slot-scope="scope">
            {{ scope.row.integrityRate ? scope.row.integrityRate + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="数量" prop="num" align="center" />
        <el-table-column label="已配发数量" prop="allotmentNum" align="center" min-width="100"/>
        <el-table-column label="来源" prop="sourceId" align="center" min-width="100">
          <template slot-scope="scope">
            {{ selectDictLabel(dict.type.sys_equipment_source, scope.row.sourceId,) }}
          </template>
        </el-table-column>
        <el-table-column label="性能描述" prop="performanceDesc" align="center" min-width="120"> </el-table-column>
        <el-table-column label="是否启用" prop="useStatus" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.useStatus == 0" type="success">启用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center" min-width="170">
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" min-width="190" class-name="small-padding fixed-width">
          <div class="table-option" slot-scope="scope" v-if="scope.row.roleId !== 1">
            <span @click="handleDetail(scope.row)">详情</span>
            <span @click="handleEquipmentWhere(scope.row)">装备去向</span>
            <span @click="handleEdit(scope.row)">编辑</span>
            <span class="danger" @click="handleDelete(scope.row)">删除</span>
          </div>
        </el-table-column>
      </el-table>

      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 用户导入对话框 -->
    <el-dialog title="导入装备情况" :visible.sync="uploadialog" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="fileHeaders" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>

          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="downloadExcel">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="uploadDisable" :loading="uploadDisable" @click="submitFileForm">确
          定</el-button>
        <el-button @click="uploadialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <Edit :title="editTitle" :actionType="actionType" :equipmentInfo="equipmentInfo" :visible.sync="editDialog"
      @close="getList"></Edit>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { equipmentList, deleteEquipment, downEquipmentInfo } from '@/api/equipment';
import Edit from './components/edit.vue';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getDeptName } from "@/utils/ruoyi";
export default {
  dicts: ['sys_equipment_source'],
  components: {
    Edit,
    Treeselect
  },
  data () {
    return {
      uploadDisable: false,
      fileHeaders: {
        Authorization: "Bearer " + getToken()
      },
      upload: {
        isUploading: false,
        updateSupport: 0,
        url: process.env.VUE_APP_BASE_API + '/equipment/import',
      },
      createTime: [],
      uploadialog: false,
      actionType: 'add',
      equipmentInfo: {},
      editTitle: '',
      editDialog: false,
      dataList: [],
      loading: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    deptTreeList () {
      return this.$store.state.user.deptTreeList
    },
    deptList () {
      return this.$store.state.user.deptList
    },
  },
  created () {
    this.getList();
  },

  methods: {
    // // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.uploadialog = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.uploadDisable = false;
      if(response.code == 200){
        this.$message.success('导入成功！')
      }else{
        this.$message.error(response.msg)
      }
      this.getList();
    },
    // // 提交上传文件
    submitFileForm () {
      this.uploadDisable = true;
      this.$refs.upload.submit();
    },
    downloadExcel () {
      let a = document.createElement('a')
      a.href = '/static/equipment_template.xlsx'
      a.download = '装备导入模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    // 导入文件
    handleUploadFile () {
      this.uploadialog = true
    },
    getDeptName (id) {
      return getDeptName(this.deptList, id)
    },
    // 导出装备
    async handleDownLoad () {
      let params = {
        ...this.queryParams,
      }
      let res = await downEquipmentInfo(params)
      let blob = new Blob([res], {
        type: "application/octet-stream"
      });
      let objectUrl = URL.createObjectURL(blob);
      let a = document.createElement("a");
      a.href = objectUrl;
      a.setAttribute("download", "装备信息.xlsx");
      a.click();
      window.URL.revokeObjectURL(blob);
    },
    // 查看装备去向
    handleEquipmentWhere(row) {
      this.$router.push({ path: 'issueDestination', query: { equipmentName: row.equipmentName } })
    },
    handleDetail (row) {
      this.actionType = 'look';
      this.equipmentInfo = JSON.parse(JSON.stringify(row));;
      this.editTitle = '装备详情';
      this.editDialog = true;
    },
    // 编辑装备
    handleEdit (row) {
      this.actionType = 'edit';
      this.equipmentInfo = JSON.parse(JSON.stringify(row));
      this.editTitle = '编辑装备';
      this.editDialog = true;
    },
    // 新增装备
    handleAdd () {
      this.actionType = 'add';
      this.editTitle = '新增装备';
      this.equipmentInfo = {};
      this.editDialog = true;
    },
    // 查询
    async getList () {
      this.loading = true;
      let params = {
        ...this.queryParams,
      }
      if (this.createTime && this.createTime.length > 0) {
        params.startTime = this.createTime[0]
        params.endTime = this.createTime[1]
      }
      const res = await equipmentList(params);
      this.loading = false;
      if (res.code === 200) {
        this.dataList = res.rows || [];
        this.total = res.total || 0;
      } else {
        this.dataList = [];
        this.total = 0;
      }
    },
    // 查询
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery () {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.createTime=[]
      this.handleQuery();
    },
    // 删除列表某一条数据
    handleDelete (row) {
      let that = this;
      this.$modal
        .confirm('是否确认删除？')
        .then(async function (res) {
          if (res == 'confirm') {
            let response = await deleteEquipment(row.id)
            if (response.code == 200) {
              that.$message.success('删除成功')
            } else {
              that.$message.error(response.msg)
            }
          }
        })
        .then(() => {
          this.getList();
        })
    },
  },
};
</script>
